﻿@{
    ViewData["Title"] = "组织机构管理";
}

<!-- 引入资源：Vue3、Axios、Element Plus -->
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
<script src="//unpkg.com/element-plus"></script>

<div id="app">
    <!-- 1. 查询条件区域 -->
    <div class="search-area">
        <label>组织：</label>
        <el-input v-model="searchParams.keyword" placeholder="请输入组织名称/编号" class="search-input" clearable></el-input>

        <label>状态：</label>
        <el-select v-model="searchParams.statusCode" placeholder="请选择" class="search-select" clearable>
            <el-option v-for="item in statusOptions"
                       :key="item.value"
                       :value="item.value"
                       :label="item.label">
            </el-option>
        </el-select>

        <el-button type="default" v-on:click="resetSearch" class="reset-btn">重置</el-button>
        <el-button type="primary" v-on:click="queryData" class="query-btn" style="background-color: #28a745; border-color: #28a745;">查询</el-button>
    </div>

    <!-- 2. 操作按钮区域 -->
    <div class="action-buttons">
        <el-button type="primary" v-on:click="addNew" style="background-color: #28a745; border-color: #28a745;">新增</el-button>
        <el-button type="danger" v-on:click="batchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
    </div>

    <!-- 加载中提示 -->
    <div v-loading="loading"
         element-loading-text="正在加载数据..."
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.7)">
        <div class="table-container">
            <el-table :data="tableData"
                      border
                      striped
                      style="width: 100%; margin-top: 10px;"
                      :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold' ,textAlign: 'center' }"
                      :cell-style="({ column }) => column.columnKey === 'orgNameColumn' ? { padding: '12px 8px', textAlign: 'left' } : { padding: '12px 8px', textAlign: 'center' }"
                      v-on:selection-change="handleSelectionChange">
                <!-- 表格列定义 -->
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" label="序号" width="60"></el-table-column>
                <el-table-column prop="orgCode" label="组织编号" width="120"></el-table-column>
                <el-table-column label="组织名称"
                                 width="180px"
                                 column-key="orgNameColumn">
                    <template #default="scope">
                        <span v-html="formatOrgName(scope.row)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="orgLevel" label="层级" width="80"></el-table-column>
                <el-table-column prop="orgStatus" label="状态" width="80">
                    <template #default="scope">
                        <el-tag :type="scope.row.orgStatus === '启用' ? 'success' : 'danger'">
                            {{ scope.row.orgStatus }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="orgRemark" label="备注" width="150"></el-table-column>
                <el-table-column label="操作" width="140">
                    <template #default="scope">
                        <div style="text-align: center;">
                            <el-button type="text" v-on:click="editItem(scope.row)">编辑</el-button>
                            <el-button type="text" v-on:click="deleteItem(scope.row)" style="color: #f56c6c;">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>

    <!-- 新增/编辑抽屉 -->
    <el-drawer :title="isEdit ? '编辑组织' : '新增组织'"
               v-model="drawerVisible"
               direction="rtl"
               size="50%">
        <el-form :model="form"
                 :rules="formRules"
                 ref="formRef"
                 label-width="100px"
                 class="add-form"
                 label-position="top">
            <!-- 第一行：上级分类 + 组织编号 -->
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="上级分类" prop="parentOrgId">
                        <el-tree-select v-model.number="form.parentOrgId"
                                        :data="orgTreeData"
                                        placeholder="请选择"
                                        class="full-width"
                                        :filterable="true"
                                        node-key="orgId"
                                        :default-expand-all="true"
                                        v-on:change="handleParentChange"
                                        style="height: 36px;">
                        </el-tree-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="组织编号 *" prop="orgCode">
                        <el-input v-model="form.orgCode"
                                  :readonly="isEdit"
                                  :placeholder="isEdit ? '组织编号不可修改' : '请手动输入组织编号（如XS001）'"
                                  class="full-width">
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第二行：组织名称 + 层级（编辑时可修改） -->
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="组织名称 *" prop="orgName">
                        <el-input v-model="form.orgName" placeholder="请输入组织名称" class="full-width"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="组织层级 *" prop="orgLevel">
                        <!-- 移除readonly，允许编辑 -->
                        <el-input v-model.number="form.orgLevel" placeholder="选择上级分类后自动生成或手动修改" class="full-width"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第三行：状态 -->
            <el-row :gutter="24">
                <el-col :span="24">
                    <el-form-item label="状态 *" prop="orgStatusCode">
                        <el-radio-group v-model="form.orgStatusCode" class="status-radio-group">
                            <el-radio v-for="item in statusOptions"
                                      :key="item.value"
                                      :label="item.value"
                                      border>
                                {{ item.label }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第四行：备注 -->
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="备注" prop="orgRemark">
                        <el-input v-model="form.orgRemark" type="textarea" placeholder="请输入备注" :rows="4" class="full-width"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 底部按钮 -->
            <el-form-item class="form-footer">
                <el-button v-on:click="closeDrawer">取消</el-button>
                <el-button type="primary" v-on:click="submitForm" style="background-color: #28a745; border-color: #28a745;">保存</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
</div>

<style>
    .table-container {
        width: 100%;
        margin: 0;
        overflow: hidden;
    }

    .search-area {
        margin: 10px 0;
        padding: 15px;
        background: #f5f7fa;
        border-radius: 4px;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 15px;
    }

    .search-input, .search-select {
        width: 200px;
    }

    .action-buttons {
        margin: 15px 0;
        padding-left: 10px;
        display: flex;
        gap: 10px;
    }

        .search-area .el-button, .action-buttons .el-button {
            padding: 8px 16px;
            font-size: 14px;
            border-radius: 4px;
        }

    .add-form {
        padding: 20px;
    }

    .full-width {
        width: 100%;
    }

    .status-radio-group {
        display: flex;
        gap: 20px;
        margin-top: 5px;
    }

        .status-radio-group .el-radio {
            padding: 5px 15px;
        }

    .form-footer {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        margin-top: 20px;
    }

    .el-table {
        width: 100% !important;
    }

    .el-table__header-wrapper .el-table__header {
        border-top: none !important;
    }

    .el-tree-select .el-tree {
        max-height: 200px;
        overflow-y: auto;
    }

        .el-tree-select .el-tree::-webkit-scrollbar {
            width: 6px;
        }

        .el-tree-select .el-tree::-webkit-scrollbar-thumb {
            background-color: #ddd;
            border-radius: 3px;
        }

        .el-tree-select .el-tree::-webkit-scrollbar-track {
            background-color: #f5f5f5;
        }
</style>

<script>
    const { createApp, ref, reactive, onMounted } = Vue;
    const app = createApp({
        setup() {
            // 响应式数据
            const orgList = ref([]);
            const orgTreeData = ref([]);
            const tableData = ref([]);
            const statusOptions = ref([]);
            const selectedRows = ref([]);
            const loading = ref(false);
            const drawerVisible = ref(false);
            const isEdit = ref(false);
            const formRef = ref(null);

            // 搜索参数
            const searchParams = reactive({
                keyword: "",
                statusCode: ""
            });

            // 表单数据
            const form = reactive({
                orgId: 0,
                parentOrgId: 0,
                orgCode: '',
                orgName: '',
                orgLevel: 1,
                orgStatusCode: '',
                orgStatus: '',
                orgRemark: ''
            });

            // 表单验证规则
            const formRules = reactive({
                orgCode: [
                    { required: true, message: '请输入组织编号', trigger: 'blur' },
                    { min: 2, max: 50, message: '编号长度在2-50个字符之间', trigger: 'blur' },
                    {
                        validator: async (rule, value, callback) => {
                            // 编辑时直接跳过编号唯一性校验
                            if (isEdit.value) {
                                callback();
                                return;
                            }
                            // 新增时才校验编号唯一性
                            if (!value) return callback();
                            try {
                                const res = await axios.get(`/Organization/check-code?code=${value.trim()}`);
                                if (res.data.exists) {
                                    callback(new Error(`组织编号 "${value}" 已存在，请更换`));
                                } else {
                                    callback();
                                }
                            } catch (err) {
                                callback(new Error('校验编号失败，请稍后重试'));
                            }
                        },
                        trigger: ['blur', 'change']
                    }
                ],
                orgName: [
                    { required: true, message: '请输入组织名称', trigger: 'blur' },
                    { min: 2, max: 100, message: '名称长度在2-100个字符之间', trigger: 'blur' }
                ],
                orgLevel: [
                    { required: true, message: '请输入组织层级', trigger: 'blur' },
                    { type: 'number', message: '层级必须为数字', trigger: 'blur' },
                    // { min: 1, message: '层级不能小于1', trigger: 'blur' }
                ],
                orgStatusCode: [
                    { required: true, message: '请选择组织状态', trigger: 'change' }
                ]
            });

            // API请求封装
            const api = {
                getStatusDict: () => axios.get('/Organization/dropdown/status?dictTypeCode=sys_normal_statu'),
                getOrgList: (params) => axios.get('/Organization/query', { params }),
                getAllOrgList: () => axios.get('/Organization/list'),
                getOrgById: (id) => axios.get(`/Organization/${id}`),
                addOrg: (data) => axios.post('/Organization', data),
                updateOrg: (data) => axios.put('/Organization', data),
                deleteOrg: (id) => axios.delete(`/Organization/${id}`),
                batchDeleteOrg: (ids) => axios.post('/Organization/batch-delete', ids),
                generateCodeByParent: (parentOrgId) => axios.get(`/Organization/generate-code-by-parent?parentOrgId=${parentOrgId}`)
            };

            // 初始化数据
            const init = async () => {
                await loadStatusDict();
                await loadAllOrgList();
                await queryData();
            };

            // 加载状态字典
            const loadStatusDict = async () => {
                try {
                    const res = await api.getStatusDict();
                    if (res.data.code === 200) {
                        statusOptions.value = res.data.data || [];
                        if (statusOptions.value.length > 0) {
                            form.orgStatusCode = statusOptions.value[0].value;
                        }
                    }
                } catch (err) {
                    console.error('加载状态字典失败：', err);
                    ElementPlus.ElMessage.error('加载状态数据失败，请刷新页面重试');
                }
            };

            // 加载所有组织列表
            const loadAllOrgList = async () => {
                try {
                    loading.value = true;
                    console.log("开始加载组织列表");
                    const res = await api.getAllOrgList();
                    if (res.data.code === 200) {
                        orgList.value = res.data.data || [];
                        orgTreeData.value = convertToTree(orgList.value);
                    } else {
                        ElementPlus.ElMessage.error(res.data.msg || '加载组织列表失败');
                    }
                } catch (err) {
                    console.error('加载组织列表失败：', err);
                    ElementPlus.ElMessage.error('加载组织列表失败，请刷新页面');
                } finally {
                    loading.value = false;
                    console.log("加载组织列表完成，loading重置为false");
                }
            };

            // 平级数据转树形结构
            const convertToTree = (list, parentId = 0) => {
                return list
                    .filter(item => item.parentOrgId === parentId)
                    .map(item => ({
                        orgId: item.orgId,
                        label: item.orgName,
                        orgCode: item.orgCode,
                        orgLevel: item.orgLevel,
                        children: convertToTree(list, item.orgId)
                    }));
            };

            // 上级分类变更处理：自动计算层级 + 编辑时生成编号
            const handleParentChange = async (selectedOrgId) => {
                const numericOrgId = Number(selectedOrgId);
                const selectedOrg = orgList.value.find(item => item.orgId === numericOrgId);

                // 1. 计算层级（原有逻辑）
                if (selectedOrg) {
                    form.orgLevel = selectedOrg.orgLevel + 1; // 层级 = 上级层级 + 1
                } else {
                    form.orgLevel = 1; // 无上级时为1级
                }

                // 2. 编辑状态下，根据上级组织生成orgCode
                if (isEdit.value) {
                    try {
                        // 调用后端接口生成编号
                        const res = await api.generateCodeByParent(numericOrgId);
                        if (res.data.code === 200) {
                            form.orgCode = res.data.data; // 自动填充生成的编号
                        }
                    } catch (err) {
                        console.error('编辑时生成编号失败：', err);
                        ElementPlus.ElMessage.error('生成组织编号失败，请手动检查');
                    }
                }
            };

            // 查询数据
            const queryData = async () => {
                try {
                    loading.value = true;
                    // 映射编码为状态名称（0→启用，1→停用）
                    const statusMap = { "0": "启用", "1": "停用" };
                    const res = await api.getOrgList({
                        keyword: searchParams.keyword,
                        status: statusMap[searchParams.statusCode] || ""
                    });
                    tableData.value = res.data.data || [];
                } catch (err) {
                    ElementPlus.ElMessage.error('查询失败，请重试');
                } finally {
                    loading.value = false;
                }
            };
            // 重置搜索
            const resetSearch = () => {
                searchParams.keyword = "";
                searchParams.statusCode = "";
                queryData();
            };

            // 打开新增抽屉（默认上级为福泰物流公司机构）
            const addNew = async () => {
                isEdit.value = false;
                formRef.value?.resetFields();

                // 查找福泰物流公司机构的ID和层级
                const futaiOrg = orgList.value.find(item => item.orgName === '福泰物流公司机构');
                if (futaiOrg) {
                    form.parentOrgId = futaiOrg.orgId; // 默认上级ID
                    form.orgLevel = futaiOrg.orgLevel + 1; // 层级 = 福泰物流层级 + 1（通常为2级）
                } else {
                    form.parentOrgId = 0;
                    form.orgLevel = 1;
                }

                // 重置其他表单值
                form.orgId = 0;
                form.orgCode = '';
                form.orgName = '';
                form.orgRemark = '';
                form.orgStatusCode = statusOptions.value[0]?.value || '1';

                drawerVisible.value = true;
            };

            // 打开编辑抽屉
            const editItem = async (row) => {
                loading.value = true;
                try {
                    const res = await api.getOrgById(row.orgId);
                    if (res.data.code === 200) {
                        const data = res.data.data;

                        // 查找对应的状态选项
                        const statusOption = statusOptions.value.find(item =>
                            item.label === data.orgStatus || item.value === data.orgStatusCode
                        );

                        Object.assign(form, {
                            orgId: data.orgId,
                            parentOrgId: data.parentOrgId || 0,
                            orgCode: data.orgCode,
                            orgName: data.orgName,
                            orgLevel: data.orgLevel,
                            orgStatusCode: statusOption?.value || data.orgStatusCode || '',
                            orgRemark: data.orgRemark || ''
                        });

                        isEdit.value = true;
                        drawerVisible.value = true;
                    }
                } catch (err) {
                    console.error('编辑失败：', err);
                    ElementPlus.ElMessage.error('获取组织详情失败');
                } finally {
                    loading.value = false;
                }
            };


            // 提交表单
            const submitForm = async () => {
                try {
                    await formRef.value.validate();
                } catch (error) {
                    ElementPlus.ElMessage.warning('请完善表单信息');
                    return;
                }

                // 构建提交数据
                const submitData = {
                    orgId: isEdit.value ? Number(form.orgId) : 0,
                    parentOrgId: Number(form.parentOrgId) || 0,
                    orgCode: form.orgCode.trim(),
                    orgName: form.orgName.trim(),
                    orgLevel: Number(form.orgLevel),
                    orgStatus: statusOptions.value.find(item => item.value === form.orgStatusCode)?.label || '启用',
                    orgShortName: "", // 明确设置
                    orgRemark: form.orgRemark?.trim() || ""
                };

                console.log('准备提交的数据:', JSON.stringify(submitData, null, 2));
                console.log('操作类型:', isEdit.value ? '编辑' : '新增');

                try {
                    let res;
                    if (isEdit.value) {
                        res = await api.updateOrg(submitData);
                    } else {
                        res = await api.addOrg(submitData);
                    }

                    if (res.data.success) {
                        ElementPlus.ElMessage.success(isEdit.value ? '编辑成功' : '新增成功');
                        closeDrawer();
                        // 关键：确保两个异步方法执行完毕后再关闭loading
                        await Promise.all([loadAllOrgList(), queryData()]);
                    } else {
                        ElementPlus.ElMessage.error(res.data.msg || (isEdit.value ? '编辑失败' : '新增失败'));
                    }
                } catch (err) {
                    console.error('提交错误详情:', err);
                    const errorMsg = err.response?.data?.msg || err.message || '网络错误，请检查后端服务';
                    ElementPlus.ElMessage.error(`操作失败：${errorMsg}`);
                } finally {
                    // 若以上流程异常，确保loading最终被重置
                    loading.value = false;
                }
            };

            // 关闭抽屉
            const closeDrawer = () => {
                drawerVisible.value = false;
                setTimeout(() => formRef.value?.resetFields(), 300);
            };

            // 选择行变化
            const handleSelectionChange = (rows) => {
                selectedRows.value = rows;
            };

            // 格式化组织名称（层级缩进）
            const formatOrgName = (row) => {
                if (!row.parentOrgId || row.parentOrgId === 0) return row.orgName || '';
                let parentId = row.parentOrgId;
                const prefixes = [];
                while (parentId && parentId !== 0) {
                    const parent = orgList.value.find(item => item.orgId === parentId);
                    if (!parent) break;
                    const siblings = orgList.value.filter(item => item.parentOrgId === parent.parentOrgId);
                    prefixes.unshift(siblings[siblings.length - 1]?.orgId === parent.orgId ? '&nbsp;&nbsp;' : '│&nbsp;');
                    parentId = parent.parentOrgId;
                }
                return `${prefixes.join('')}└─&nbsp;${row.orgName || ''}`;
            };

            // 删除单个组织
            const deleteItem = async (row) => {
                ElementPlus.ElMessageBox.confirm(
                    `确定要删除组织【${row.orgName}】吗？`,
                    '删除确认',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(async () => {
                    try {
                        const res = await api.deleteOrg(row.orgId);
                        if (res.data.success) {
                            ElementPlus.ElMessage.success('删除成功');
                            await queryData();
                        } else {
                            ElementPlus.ElMessage.error(res.data.msg || '删除失败');
                        }
                    } catch (err) {
                        console.error('删除失败：', err);
                        ElementPlus.ElMessage.error('删除失败，请重试');
                    }
                }).catch(() => {
                    ElementPlus.ElMessage.info('已取消删除');
                });
            };

            // 批量删除
            const batchDelete = async () => {
                if (selectedRows.value.length === 0) return;

                const orgNames = selectedRows.value.map(row => row.orgName).join('、');
                ElementPlus.ElMessageBox.confirm(
                    `确定要删除选中的【${orgNames}】等${selectedRows.value.length}个组织吗？`,
                    '批量删除确认',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(async () => {
                    try {
                        const ids = selectedRows.value.map(row => row.orgId);
                        const res = await api.batchDeleteOrg(ids);
                        if (res.data.success) {
                            ElementPlus.ElMessage.success('批量删除成功');
                            selectedRows.value = [];
                            await queryData();
                        } else {
                            ElementPlus.ElMessage.error(res.data.msg || '批量删除失败');
                        }
                    } catch (err) {
                        console.error('批量删除失败：', err);
                        ElementPlus.ElMessage.error('批量删除失败，请重试');
                    }
                }).catch(() => {
                    ElementPlus.ElMessage.info('已取消批量删除');
                });
            };

            // 页面加载时初始化
            onMounted(() => init());

            return {
                orgList, orgTreeData, tableData, statusOptions,
                selectedRows, loading, drawerVisible, isEdit,
                searchParams, form, formRules, formRef,

                queryData, resetSearch, handleSelectionChange,
                formatOrgName, addNew, editItem, closeDrawer,
                submitForm, deleteItem, batchDelete, handleParentChange
            };
        }
    });
    app.use(ElementPlus);
    app.mount("#app");
</script>